package br.org.group.android.dao;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import br.org.group.android.app.R;

public class ImportFortunes {

	public void Popula(SQLiteDatabase db, Context ctx) {

		InputStream ins = ctx.getResources().openRawResource(R.raw.brazilian);

		int id = 0;
		ArrayList<FortunesDAO> fortunes = new ArrayList<FortunesDAO>();

		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(ins,
					"UTF8"), 1024);
			while (in.ready()) {
				FortunesDAO f = readFortune(in);
				f.setId(++id);
				fortunes.add(f);
			}

			if (in != null) {
				in.close();
			}
		} catch (IOException e) {
			System.out.println("Não achei o arquivo fortunes");
		}

		for (FortunesDAO fdao : fortunes) {

			ContentValues cv = new ContentValues();
			cv.put(FortunesDbAdapter.KEY_MSG, fdao.getMensagem());
			cv.put(FortunesDbAdapter.KEY_AUTHOR, fdao.getAutor());
			cv.put(FortunesDbAdapter.KEY_STATUS, FortunesDAO.NAO_LIDO);

			db.insert(FortunesDbAdapter.FORTUNES_TABLE, null, cv);
		}
	}

	private static FortunesDAO readFortune(BufferedReader in) {
		FortunesDAO fortune = new FortunesDAO();
		String line = "";
		while (line == null || !line.startsWith("%")) {
			try {
				line = in.readLine();

				if (line != null && !line.startsWith("%")) {
					if (line.replace(" ", "").replace("\t", "")
							.startsWith("--")) {
						fortune.setAutor(line.replace("\t", "").replace("--",
								""));

						line = in.readLine();
						while (line != null && !line.startsWith("%")) {
							fortune.setAutor(fortune.getAutor() + line);
							line = in.readLine();
						}
					} else {
						fortune.setMensagem(fortune.getMensagem() + line);
					}
				}
				if (line == null) {
					break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		fortune.setMensagem(fortune.getMensagem().replace("\t"," ").replace("\n",""));
		return fortune;
	}
}
